﻿using System;
using System.Threading.Tasks;

namespace RockBus.Threading
{
    public static class EventHandlerExtensions
    {
        public static void Fire<T>(this EventHandler<T> eventHandler, object sender, T eventArgs)
        {
            if (eventHandler == null)
            {
                return;
            }

            foreach (var dlgt in eventHandler.GetInvocationList())
            {
                try
                {
                    dlgt.DynamicInvoke(sender, eventArgs);
                }
                catch { }
            }
        }

        public static void FireParallel<T>(this EventHandler<T> eventHandler, object sender, T eventArgs)
        {
            if (eventHandler == null)
            {
                return;
            }

            Parallel.ForEach(eventHandler.GetInvocationList(), (dlgt) =>
            {
                try
                {
                    dlgt.DynamicInvoke(sender, eventArgs);
                }
                catch { }
            });
        }
    }
}